package com.web.controller.api;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.web.annotation.UserAccess;
import com.web.dao.*;
import com.web.domain.ApiResponse;
import com.web.dto.*;
import com.web.entity.*;
import com.web.manager.StoreApplyManager;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;


/**
 * @author FDjavaone
 * @date 2017/8/24
 */
@RestController
@RequestMapping("api")
public class StoreController {
    @Autowired
    private StoreApplyMapper storeApplyMapper;
    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private StoreChangeMapper storeChangeMapper;

    @Autowired
    private StoreApplyManager storeApplyManager;
    @Autowired
    private KftApplyMapper kftApplyMapper;


    /**
     * 个人商户申请
     */
    @UserAccess
    @RequestMapping("/app/store/personApply")
    public ApiResponse personApply(StoreApplyDto storeApplyDto, HttpServletRequest req, HttpServletResponse resp) throws Exception {
        storeApplyDto.setStoreType("1");
            //System.out.println(storeApplyDto);
        return storeApplyManager.apply( storeApplyDto );
    }

    /**
     * 个人商户申请编辑
     */
    @UserAccess
    @RequestMapping("/app/store/personApplyEdit")
    public ApiResponse personApplyEdit(StoreApplyDto storeApplyDto, HttpServletRequest req, HttpServletResponse resp) throws Exception {
        storeApplyDto.setStoreType( "1" );
        return storeApplyManager.applyEditNew(storeApplyDto);
    }

    /**
     * 商铺申请
     */
    @UserAccess
    @RequestMapping("/app/store/apply")
    public ApiResponse apply(StoreApply storeApply, HttpServletRequest req, HttpServletResponse resp) {
        ApiResponse response = new ApiResponse();
        Date date = new Date();
        storeApply.setCreateTime(date);
        storeApply.setModifyTime(date);
        storeApplyMapper.insertSelective(storeApply);
        response.setMessage("申请提交成功！");
        response.setStatus(900000);
        return response;
    }


    /**
     * 商铺申请（新）
     */
    @UserAccess
    @RequestMapping("/app/store/applyNew")
    public ApiResponse applyNew(StoreApplyDto storeApplyDto, HttpServletRequest req, HttpServletResponse resp) throws Exception {
        storeApplyDto.setStoreType("2");
        return storeApplyManager.apply(storeApplyDto);

    }

    /**
     * 商铺申请编辑
     */
    @UserAccess
    @RequestMapping("/app/store/applyEdit")
    public ApiResponse applyEdit(StoreApply storeApply, HttpServletRequest req, HttpServletResponse resp) {
        ApiResponse response = new ApiResponse();
        Date date = new Date();
        storeApply.setCreateTime(date);
        storeApply.setModifyTime(date);
        storeApply.setStatus(0);
        storeApplyMapper.updateByPrimaryKeySelective(storeApply);
        response.setMessage("申请重新提交成功！");
        response.setStatus(900000);
        return response;
    }

    /**
     * 商铺申请编辑（新）
     */
    @UserAccess
    @RequestMapping("/app/store/applyEditNew")
    public ApiResponse applyEditNew(StoreApplyDto storeApplyDto, HttpServletRequest req, HttpServletResponse resp) throws Exception {
        storeApplyDto.setStoreType("2");
        return storeApplyManager.applyEditNew(storeApplyDto);
    }

    /**
     * 企业申请
     */
    @UserAccess
    @RequestMapping("/app/store/enterpriseApply")
    public ApiResponse enterpriseApply(StoreApply storeApply, HttpServletRequest req, HttpServletResponse resp) {
        ApiResponse response = new ApiResponse();
        Date date = new Date();
        storeApply.setType("企业");
        storeApply.setCreateTime(date);
        storeApply.setModifyTime(date);
        storeApplyMapper.insertSelective(storeApply);
        response.setMessage("申请提交成功！");
        response.setStatus(900000);
        return response;
    }
    /**
     * 企业申请(新)
     */
    @UserAccess
    @RequestMapping("/app/store/enterpriseApplyNew")
    public ApiResponse enterpriseApplyNew(StoreApplyDto storeApplyDto, HttpServletRequest req, HttpServletResponse resp) throws Exception {
        storeApplyDto.setType("企业");
        storeApplyDto.setStoreType("3");
        return storeApplyManager.apply(storeApplyDto);
    }
    /**
     * 获取快付通注册信息
     */
    @UserAccess
    @RequestMapping("/app/store/getKftApply")
    public ApiResponse getKftApply(StoreApplyDto storeApplyDto, HttpServletRequest req, HttpServletResponse resp) throws Exception {
        KftApply kftApply=kftApplyMapper.findByMid(storeApplyDto.getMId());
        ApiResponse response = new ApiResponse();
        response.setParams(kftApply);
        response.setStatus(900000);
        response.setMessage("信息查询成功！");
        return response;
    }

    /**
     * 企业申请编辑
     */
    @UserAccess
    @RequestMapping("/app/store/enterpriseApplyEdit")
    public ApiResponse enterpriseApplyEdit(StoreApply storeApply, HttpServletRequest req, HttpServletResponse resp) {
        ApiResponse response = new ApiResponse();
        Date date = new Date();
        storeApply.setType("企业");
        storeApply.setCreateTime(date);
        storeApply.setModifyTime(date);
        storeApply.setStatus(0);
        storeApplyMapper.updateByPrimaryKeySelective(storeApply);
        response.setMessage("申请重新提交成功！");
        response.setStatus(900000);
        return response;
    }

    /**
     * 企业申请编辑（新）
     */
    @UserAccess
    @RequestMapping("/app/store/enterpriseApplyEditNew")
    public ApiResponse enterpriseApplyEditNew(StoreApplyDto storeApplyDto, HttpServletRequest req, HttpServletResponse resp) throws Exception {
        storeApplyDto.setType("企业");
        storeApplyDto.setStoreType("3");
        return storeApplyManager.applyEditNew(storeApplyDto);
    }

    /**
     * 店铺首页
     */
    @UserAccess
    @RequestMapping("/app/store/index")
    public ApiResponse index(Store s, HttpServletRequest req, HttpServletResponse resp) {
        ApiResponse response = new ApiResponse();
        Store store = storeMapper.selectByMid(s.getmId());
        if (store == null) {
            response.setMessage("商户尚未入驻！");
            response.setStatus(900301);
            //获取入驻状态
            List<StoreApply> storeApplies = storeApplyMapper.selectByMid(s.getmId());

            response.setParams(storeApplies);
            return response;
        }
        Calendar start = Calendar.getInstance();
        start.set(Calendar.HOUR_OF_DAY, 00);
        start.set(Calendar.MINUTE, 00);
        start.set(Calendar.SECOND, 00);
        start.set(Calendar.DATE, start.get(Calendar.DATE));
        BigDecimal todayBusiness = new BigDecimal(0);
        List<Order> orders = orderMapper.selectFinishByTimeLimit(start.getTime(), store.getId());
        for (Order d : orders) {
            todayBusiness = todayBusiness.add(d.getTotalPrice());
        }
        Map map = new HashMap();
        map.put("name", store.getMerchantName());
        if (store.getLogo() == null) {
            map.put("logo", "");
        } else {
            map.put("logo", store.getLogo());
        }

        if (store.getMerchantImg() == null) {
            map.put("merchantImg", "");
        } else {
            map.put("merchantImg", store.getMerchantImg());
        }
        if (store.getStoreImg() == null) {
            map.put("storeImg", "");
        } else {
            map.put("storeImg", store.getStoreImg());
        }
        map.put("businessStatus", store.getBusinessStatus());
        map.put("storeId", store.getId());
        map.put("level", store.getLevel());
        map.put("todayBusiness", todayBusiness);
        map.put("type", store.getType());
        response.setParams(map);
        response.setMessage("数据获取成功！");
        response.setStatus(900000);
        return response;
    }

    /**
     * 修改logo
     */
    @UserAccess
    @RequestMapping("/app/store/logoChange")
    public ApiResponse logoChange(Store store, HttpServletRequest req, HttpServletResponse resp) {
        ApiResponse response = new ApiResponse();
        Date date = new Date();
        store.setModifyTime(date);
        storeMapper.updateByPrimaryKeySelective(store);
        response.setMessage("商户logo修改成功！");
        response.setStatus(900000);
        return response;
    }

    /**
     * 店铺参数修改申请创建
     */
    @UserAccess
    @RequestMapping("/app/store/change")
    public ApiResponse change(StoreChange storeChange, HttpServletRequest req, HttpServletResponse resp) {
        ApiResponse response = new ApiResponse();
        Date date = new Date();
        storeChange.setCreateTime(date);
        storeChange.setModifyTime(date);
        StoreChange old = storeChangeMapper.selectHasNotFinish(storeChange);
        if (old == null) {
            storeChangeMapper.insertSelective(storeChange);
        } else {
            storeChange.setId(old.getId());
            storeChangeMapper.updateByPrimaryKeySelective(storeChange);
        }
        response.setMessage("修改申请提交成功！");
        response.setStatus(900000);
        return response;
    }


    /**
     * 订单列表
     */
    @UserAccess
    @RequestMapping("/app/store/orderList")
    public ApiResponse orderList(PageDto pageDto, HttpServletRequest req, HttpServletResponse resp) {
        ApiResponse response = new ApiResponse();
        PageHelper.startPage(pageDto.getPageNum(), pageDto.getPageSize());
        List<Order> orders = orderMapper.selectByStoreId(pageDto.getId());
        for(Order o:orders){
            if(o.getName()==null||"".equals(o.getName())){
                Member member=memberMapper.selectByPrimaryKey(o.getmId());
                if(member!=null&&member.getName()!=null){
                    o.setName(member.getName());
                }
            }
        }
        PageInfo page = new PageInfo(orders);
        response.setParams(page);
        response.setMessage("订单获取成功！");
        response.setStatus(900000);
        return response;
    }

    /**
     * 店铺营业状态切换
     */
    @UserAccess
    @RequestMapping("/app/store/switchBusiness")
    public ApiResponse switchBusiness(Store store, HttpServletRequest req, HttpServletResponse resp) {
        ApiResponse response = new ApiResponse();
        boolean flag = true;
        if (store.getBusinessStatus() == 1) {
            List<Menu> menus = menuMapper.selectByStoreId(store.getId());
            if (menus.size() == 0) {
                flag = false;
            }
        }
        if (flag) {
            Date date = new Date();
            store.setModifyTime(date);
            storeMapper.updateByPrimaryKeySelective(store);
            response.setMessage("店铺营业状态切换成功！");
            response.setStatus(900000);
        } else {
            response.setMessage("店铺营业状态切换失败！您的店铺中还未添加任何菜单和商品！");
            response.setStatus(900231);
        }

        return response;
    }

    /**
     * 店铺让利比例设置
     */
    @UserAccess
    @RequestMapping("/app/store/shareProfit")
    public ApiResponse shareProfit(Store store, HttpServletRequest req, HttpServletResponse resp) {
        ApiResponse response = new ApiResponse();
        Date date = new Date();
        store.setModifyTime(date);
        storeMapper.updateByPrimaryKeySelective(store);
        response.setMessage("店铺让利比例设置成功！");
        response.setStatus(900000);
        return response;
    }

    /**
     * 设置商户照片
     */
    @UserAccess
    @RequestMapping("/app/store/setMerchantImg")
    public ApiResponse setMerchantImg(Store store, HttpServletRequest req, HttpServletResponse resp) {
        ApiResponse response = new ApiResponse();
        Date date = new Date();
        store.setModifyTime(date);
        storeMapper.updateByPrimaryKeySelective(store);
        response.setMessage("商户照片设置成功！");
        response.setStatus(900000);
        return response;
    }

    /**
     * 店铺参数获取
     */
    @UserAccess
    @RequestMapping("/app/store/getDetail")
    public ApiResponse getDetail(Store store, HttpServletRequest req, HttpServletResponse resp) {
        ApiResponse response = new ApiResponse();
        store = storeMapper.selectByPrimaryKey(store.getId());
        StoreDto dto = new StoreDto();
        StoreChange storeChange = new StoreChange();
        storeChange.setsId(store.getId());
        StoreChange old = storeChangeMapper.selectHasNotFinish(storeChange);
        if (old != null) {
            StoreChangeDto storeChangeDto = new StoreChangeDto();
            BeanUtils.copyProperties(old, storeChangeDto);
            storeChangeDto.setChangeStatus(1);
            response.setParams(storeChangeDto);
        } else {
            BeanUtils.copyProperties(store, dto);
            dto.setChangeStatus(0);
            response.setParams(dto);
        }
        response.setMessage("基本信息获取成功！");
        response.setStatus(900000);
        return response;
    }

    /**
     * 商品管理菜单列表获取
     */
    @UserAccess
    @RequestMapping("/app/store/getMenuAndGoods")
    public ApiResponse getMenuAndGoods(Store store, HttpServletRequest req, HttpServletResponse resp) {
        ApiResponse response = new ApiResponse();
        List<Menu> menus = menuMapper.selectByStoreId(store.getId());
        List<MenuDto> menuDtos = new ArrayList<>();

        for (Menu m : menus) {
            MenuDto dto = new MenuDto();
            BeanUtils.copyProperties(m, dto);
            List<Goods> goods = goodsMapper.selectByMenuId(m.getId());
            dto.setGoods(goods);
            menuDtos.add(dto);
        }

        response.setParams(menuDtos);
        response.setMessage("菜单列表获取成功！");
        response.setStatus(900000);
        return response;
    }

    /**
     * 菜单列表获取（不包括菜单下的商品）
     */
    @UserAccess
    @RequestMapping("/app/menu/list")
    public ApiResponse menuList(Menu menu, HttpServletRequest req, HttpServletResponse resp) {
        ApiResponse response = new ApiResponse();
        List<Menu> menus = menuMapper.selectByStoreId(menu.getStoreId());
        response.setParams(menus);
        response.setMessage("菜单获取成功！");
        response.setStatus(900000);
        return response;
    }

    /**
     * 添加菜单
     */
    @UserAccess
    @RequestMapping("/app/menu/add")
    public ApiResponse menuAdd(Menu menu, HttpServletRequest req, HttpServletResponse resp) {
        ApiResponse response = new ApiResponse();
        Date date = new Date();
        menu.setCreateTime(date);
        menu.setModifyTime(date);
        menuMapper.insertSelective(menu);
        List<Menu> menus = menuMapper.selectByStoreId(menu.getStoreId());
        response.setParams(menus);
        response.setMessage("菜单添加成功！");
        response.setStatus(900000);
        return response;
    }

    /**
     * 菜单编辑
     */
    @UserAccess
    @RequestMapping("/app/menu/edit")
    public ApiResponse menuEdit(Menu menu, HttpServletRequest req, HttpServletResponse resp) {
        ApiResponse response = new ApiResponse();
        Date date = new Date();
        menu.setModifyTime(date);
        menuMapper.updateByPrimaryKeySelective(menu);
        List<Menu> menus = menuMapper.selectByStoreId(menu.getStoreId());
        response.setParams(menus);
        response.setMessage("菜单编辑成功！");
        response.setStatus(900000);
        return response;
    }

    /**
     * 菜单删除
     */
    @UserAccess
    @RequestMapping("/app/menu/del")
    public ApiResponse menuDel(Menu menu, HttpServletRequest req, HttpServletResponse resp) {
        ApiResponse response = new ApiResponse();
        menuMapper.deleteByPrimaryKey(menu.getId());
        goodsMapper.deleteByMenuId(menu.getId());
        List<Menu> menus = menuMapper.selectByStoreId(menu.getStoreId());
        response.setParams(menus);
        response.setMessage("菜单删除成功！");
        response.setStatus(900000);
        return response;
    }

    /**
     * 菜单下商品获取
     */
    @UserAccess
    @RequestMapping("/app/goods/list")
    public ApiResponse goodsList(Menu menu, HttpServletRequest req, HttpServletResponse resp) {
        ApiResponse response = new ApiResponse();
        List<Goods> goods = goodsMapper.selectByMenuId(menu.getId());
        response.setParams(goods);
        response.setMessage("商品获取成功！");
        response.setStatus(900000);
        return response;
    }

    /**
     * 商品添加
     */
    @UserAccess
    @RequestMapping("/app/goods/add")
    public ApiResponse goodsAdd(Goods good, HttpServletRequest req, HttpServletResponse resp) {
        ApiResponse response = new ApiResponse();
        Date date = new Date();
        good.setCreateTime(date);
        good.setModifyTime(date);
        goodsMapper.insertSelective(good);
        List<Goods> goods = goodsMapper.selectByMenuId(good.getMenuId());
        response.setParams(goods);
        response.setMessage("商品添加成功！");
        response.setStatus(900000);
        return response;
    }

    /**
     * 商品添加
     */
    @UserAccess
    @RequestMapping("/app/goods/edit")
    public ApiResponse goodsEdit(Goods good, HttpServletRequest req, HttpServletResponse resp) {
        ApiResponse response = new ApiResponse();
        Date date = new Date();
        good.setModifyTime(date);
        goodsMapper.updateByPrimaryKeySelective(good);
        List<Goods> goods = goodsMapper.selectByMenuId(good.getMenuId());
        response.setParams(goods);
        response.setMessage("商品编辑成功！");
        response.setStatus(900000);
        return response;
    }

    /**
     * 商品添加
     */
    @UserAccess
    @RequestMapping("/app/goods/del")
    public ApiResponse goodsDel(Goods good, HttpServletRequest req, HttpServletResponse resp) {
        ApiResponse response = new ApiResponse();
        goodsMapper.deleteByPrimaryKey(good.getId());
        List<Goods> goods = goodsMapper.selectByMenuId(good.getMenuId());
        response.setParams(goods);
        response.setMessage("商品删除成功！");
        response.setStatus(900000);
        return response;
    }

    /**
     * 企业订单列表数据
     */
    @UserAccess
    @RequestMapping("/app/store/companyOrderList")
    public ApiResponse companyOrderList(PageDto pageDto, HttpServletRequest req, HttpServletResponse resp) {
        ApiResponse response = new ApiResponse();
        PageHelper.startPage(pageDto.getPageNum(), pageDto.getPageSize());
        Order order = new Order();
        order.setStoreId(pageDto.getId());
        List<Order> orders = new ArrayList<>();
        if (pageDto.getStatus() == 0) {
            //未完成订单
            orders = orderMapper.selectUnfinishOrderByStore(order);
        } else if (pageDto.getStatus() == 1) {
            //已完成订单
            orders = orderMapper.selectFinishOrderByStoreId(order);
        }
        for(Order o:orders){
            if(o.getName()==null||"".equals(o.getName())){
                Member member=memberMapper.selectByPrimaryKey(o.getmId());
                if(member!=null&&member.getName()!=null){
                    o.setName(member.getName());
                }
            }
        }

        PageInfo page = new PageInfo(orders);
        response.setParams(page);
        response.setMessage("订单获取成功！");
        response.setStatus(900000);
        return response;
    }

    /**
     * 发货
     */
    @UserAccess
    @RequestMapping("/app/order/delivery")
    public ApiResponse delivery(Order order, HttpServletRequest req, HttpServletResponse resp) {
        ApiResponse response = new ApiResponse();
        Date date = new Date();
        Order newOrder = orderMapper.selectByPrimaryKey(order.getId());
        if (newOrder.getStatus() != 1) {
            response.setMessage("订单发货失败！");
            response.setStatus(900400);
            return response;
        }
        order.setStatus(2);
        order.setModifyTime(date);
        orderMapper.updateByPrimaryKeySelective(order);
        response.setMessage("订单发货成功！");
        response.setStatus(900000);
        return response;
    }

    /**
     * 快递单号修改
     */
    @UserAccess
    @RequestMapping("/app/order/expressNumberChange")
    public ApiResponse expressNumberChange(Order order, HttpServletRequest req, HttpServletResponse resp) {
        ApiResponse response = new ApiResponse();
        Date date = new Date();
        order.setModifyTime(date);
        orderMapper.updateByPrimaryKeySelective(order);
        response.setMessage("订单快递单号修改成功！");
        response.setStatus(900000);
        return response;
    }


    /**
     * 进入店铺的页面数据
     */
    @RequestMapping("/app/store/enter")
    public ApiResponse enter(Store store) {
        ApiResponse response = new ApiResponse();
        List<Menu> menus = menuMapper.selectByStoreId(store.getId());
        store = storeMapper.selectByPrimaryKey(store.getId());
        List<MenuDto> menuDtos = new ArrayList<>();
        for (Menu m : menus) {
            MenuDto dto = new MenuDto();
            BeanUtils.copyProperties(m, dto);
            List<Goods> goods = goodsMapper.selectByMenuId(m.getId());
            dto.setGoods(goods);
            menuDtos.add(dto);
        }
        Member member = memberMapper.selectByPrimaryKey(store.getmId());
        Map map = new HashMap();
        if (orderMapper.countOrderByMidAndNotCancel(store.getmId()) == 0) {
            map.put("hasBuy", 0);
        } else {
            map.put("hasBuy", 1);
        }

        map.put("store", store);
        map.put("menuAndGoods", menuDtos);
        map.put("member", member);

        response.setParams(map);
        response.setMessage("店铺数据获取成功！");
        response.setStatus(900000);
        return response;
    }


}
